package com.baiduspring.web.valicode;

import com.baiduspring.dao.entity.SmsCode;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.function.ucpass.SmsUtil;
import com.baiduspring.function.ucpass.StaticVar;
import com.baiduspring.service.sms.SmsCodeService;
import com.baiduspring.utils.ResponseResult;
import com.baiduspring.utils.SystemCode;
import com.baiduspring.utils.Validator;
import com.baiduspring.utils.number.MathUtils;
import com.baiduspring.utils.security.Base64Utils;
import com.baiduspring.vo.ValidateVO;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.Optional;

/**
 * 短信验证码接口
 *
 * @author xiongyan
 */
@RestController
@RequestMapping(value = "/smscode")
@Scope(value = "prototype")
public class SmsCodeController {
    @Autowired
    private SmsCodeService smsCodeService;

    @RequestMapping(value = "/send/{mobile}/{token}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult send(@PathVariable String mobile, @PathVariable String token, HttpSession session) {
        String msg = "数据错误";
        if (!Base64.isBase64(mobile) || !Base64.isBase64(token)) {
            return new ResponseResult(SystemCode.FAIL, msg);
        }
        /*
         * 验证手机号码是否正确输入
         */
        mobile = Base64Utils.decode(mobile);
        token = Base64Utils.decode(token);
        if (StringUtils.isEmpty(mobile)) {
            return new ResponseResult(SystemCode.FAIL, "手机号码不能为空");
        }
        if (!Validator.isMobile(mobile)) {
            return new ResponseResult(SystemCode.FAIL, "手机号码不合法");
        }

        String smsCodePrefix = "SMS_CODE_";
        if (Objects.nonNull(session.getAttribute(smsCodePrefix + mobile))) {
            return new ResponseResult(SystemCode.FAIL, "验证码已经发送，请在60秒后再次获取");
        }

        //随机生成短信验证码
        Integer smsCode = MathUtils.randomIntBetween(100000, 1000000);
        String result = SmsUtil.getInstance().send(token, mobile.trim(), String.valueOf(smsCode) + "," + StaticVar.SMS_CODE_VALID_DURATION);

        String respCode = com.baiduspring.utils.string.StringUtils.ucpaasRespCode(result);
        /*
         * todo 这里需要向数据库保存短信验证码的发送响应记录。PS：待做
         */
        try {
            smsCodeService.save(mobile, String.valueOf(smsCode), respCode);
        } catch (BaiduSpringException e) {
            return new ResponseResult(SystemCode.FAIL, e.getErrorMsg());
        } catch (Exception e) {
            return new ResponseResult(SystemCode.FAIL, "验证码获取失败");
        }

        String successCode = "000000";
        if (successCode.equals(respCode)) {
            //将短信验证码保存在session中
            session.setAttribute(smsCodePrefix + mobile, String.valueOf(smsCode));
            session.setMaxInactiveInterval(60);
            return new ResponseResult(SystemCode.SUCCESS, "短信验证码发送成功，请注意查收");
        } else {
            return new ResponseResult(SystemCode.FAIL, "短信验证码发送失败，请重新获取");
        }
    }

    @RequestMapping(value = "/valid/{mobile}/{smscode}", method = RequestMethod.GET)
    @ResponseBody
    public ValidateVO<String> valid(@PathVariable("mobile") String mobile, @PathVariable("smscode") String smscode) {
        if (!Base64.isBase64(mobile) || !Base64.isBase64(smscode)) {
            return new ValidateVO<>(false, "数据错误");
        }

        if (StringUtils.isEmpty(mobile)) {
            return new ValidateVO<>(false, "手机号码不能为空");
        }
        mobile = Base64Utils.decode(mobile);

        if (StringUtils.isEmpty(smscode)) {
            return new ValidateVO<>(false, "短信验证码不能为空");
        }
        smscode = Base64Utils.decode(smscode);

        Optional<SmsCode> smsCodeOptional = smsCodeService.getByMobile(Long.valueOf(mobile), smscode);

        if (smsCodeOptional.isPresent()) {
            return new ValidateVO<>(true, "验证成功");
        }

        return new ValidateVO<>(false, "短信验证码错误");
    }
}